package com.wxw.BaseLibrary.dialog;

import android.app.*;
import android.content.DialogInterface;
import android.os.Bundle;
import android.widget.DatePicker;
import com.wxw.BaseLibrary.infa.IGeneralEventCallback;

import java.text.SimpleDateFormat;
import java.util.Calendar;

public class DatePickerFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener {
    private IGeneralEventCallback onDateChangeListener;
    private IGeneralEventCallback onCancelListener;
    public static Calendar calendar = null;

    public void setOnDateChangeListener(IGeneralEventCallback onDateChangeListener) {
        this.onDateChangeListener = onDateChangeListener;
    }

    public void setOnCancelListener(IGeneralEventCallback onCancelListener) {
        this.onCancelListener = onCancelListener;
    }

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        if (calendar == null) {
            calendar = Calendar.getInstance();
        }
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH);
        int day = calendar.get(Calendar.DAY_OF_MONTH);
        return new DatePickerDialog(getActivity(), AlertDialog.THEME_DEVICE_DEFAULT_LIGHT, this, year, month, day);
    }

    @Override
    public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.YEAR, year);
        calendar.set(Calendar.MONTH, monthOfYear);
        calendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
        String s = format.format(calendar.getTime());
        if (onDateChangeListener != null) {
            onDateChangeListener.finished(this, s);
        }
    }

    @Override
    public void onCancel(DialogInterface dialog) {
        super.onCancel(dialog);
        if (onCancelListener != null) {
            onCancelListener.finished(this, "");
        }
    }

    public static DatePickerFragment show(Activity activity, String title, IGeneralEventCallback callback) {
        return show(activity, title, callback, callback);
    }

    public static DatePickerFragment show(Activity activity, String title, IGeneralEventCallback okcallback, IGeneralEventCallback cancelcallback) {
        DatePickerFragment fragment = new DatePickerFragment();
        fragment.setOnDateChangeListener(okcallback);
        fragment.setOnCancelListener(cancelcallback);
        fragment.show(activity.getFragmentManager(), title);
        return fragment;
    }
}
